<template>
  <div class="user-activities">
    <!-- 用户信息头部 -->
    <el-card shadow="hover" class="user-header">
      <div class="header-content">
        <el-avatar :src="currentUser.avatar? currentUser.avatar : defaultAvatar" :size="80" />
        <div class="user-info">
          <h2>{{ currentUser.nickname }}的行为日志</h2>
          <div class="meta-info">
            <span>注册日期: {{ formatDate(currentUser.createTime) }}</span>
          </div>
        </div>
        <el-button @click="goBack" :icon="ArrowLeft">返回用户列表</el-button>
      </div>
    </el-card>

    <!-- 筛选区域 -->
    <el-card shadow="hover" class="activities-filter">
      <div class="filter-row">
        <el-select v-model="activityType" placeholder="选择活动类型" @change="handleFilterChange">
          <el-option v-for="type in activityTypes" :key="type.value" :label="type.label" :value="type.value" />
        </el-select>
        <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" @change="handleFilterChange" />
        <el-input v-model="searchKeyword" placeholder="搜索活动内容" clearable @clear="handleFilterChange"
          @keyup.enter="handleFilterChange">
          <template #append>
            <el-button @click="handleFilterChange">搜索</el-button>
          </template>
        </el-input>
      </div>
    </el-card>

    <!-- 活动列表 -->
    <el-card shadow="hover" class="activities-list">
      <div class="activities-header">
        <h3>活动记录</h3>
        <div class="stats">
          <span>总计: {{ totalActivities }} 条记录</span>
        </div>
      </div>

      <el-empty v-if="activities.length === 0" description="暂无活动记录" />

      <div class="activity-items" v-else>
        <div v-for="activity in activities" :key="activity.id" class="activity-item" @click="viewDetail(activity)">
          <div class="activity-time">
            {{ formatDate(activity.timestamp) }}
          </div>
          <div class="activity-content">
            <div class="activity-type" :style="{ color: getActivityColor(activity.type) }">
              <el-icon :size="16">
                <component :is="getActivityIcon(activity.type)" />
              </el-icon>
              <span>{{ getActivityTypeName(activity.type) }}</span>
            </div>
            <div class="activity-text">
              {{ activity.content }}
            </div>
            <div class="activity-preview" v-if="activity.details">
              {{ activity.details.substring(0, 50) }}{{ activity.details.length > 50? '...' : '' }}
            </div>
          </div>
          <div class="activity-cover" v-if="activity.book">
            <img :src="activity.book.cover" :alt="activity.book.title" />
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination" v-if="totalActivities > 0">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentUserActivities"
          :current-page="currentPage" :page-sizes="[10, 20, 50]" :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="totalActivities" />
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" :title="`活动详情 - ${getActivityTypeName(currentActivity.type)}`" width="50%"
      @close="closeDetailDialog">
      <div class="activity-detail">
        <div class="detail-header">
          <div class="activity-time">
            {{ formatDate(currentActivity.timestamp) }}
          </div>
          <div class="activity-type" :style="{ color: getActivityColor(currentActivity.type) }">
            <el-icon :size="20">
              <component :is="getActivityIcon(currentActivity.type)" />
            </el-icon>
            <span>{{ getActivityTypeName(currentActivity.type) }}</span>
          </div>
        </div>

        <div class="detail-content">
          <h4>{{ currentActivity.content }}</h4>

          <div class="book-info" v-if="currentActivity.book">
            <img :src="currentActivity.book.cover" :alt="currentActivity.book.title" />
            <div class="book-title">{{ currentActivity.book.title }}</div>
          </div>

          <div class="activity-details" v-if="currentActivity.details">
            <h5>详细信息</h5>
            <p>{{ currentActivity.details }}</p>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="closeDetailDialog">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { ArrowLeft, User, Notebook, ChatLineRound, View, Top, Bottom, Star } from '@element-plus/icons-vue';
import { useRouter, useRoute } from 'vue-router';
import { currentUserService, userLogsService } from '@/api/user.js';
import defaultAvatar from '@/assets/my.jpg';

const router = useRouter();
const route = useRoute();

// 当前用户信息
const currentUser = ref({});

// 模拟单个用户的活动数据
const mockUserActivities = ref<any[]>([]);

// 数据状态
const activityType = ref('');
const activityTypes = ref([
  { value: '', label: '全部类型' },
  { value: 'login', label: '登录' },
  { value:'read', label: '阅读' },
  { value:'review', label: '评论' },
  { value: 'like', label: '点赞' },
  { value: 'note', label: '笔记' },
  { value: 'collect', label: '收藏' }
]);
const dateRange = ref<Array<string>>([]);
const searchKeyword = ref('');
const activities = ref<any[]>([]);
const totalActivities = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const detailDialogVisible = ref(false);
const currentActivity = ref<any>({});

// 当前日期
const currentDate = computed(() => {
  const now = new Date();
  return now.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  });
});

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-');
};

// 生命周期钩子
onMounted(() => {
  loadCurrentUser(route.query.id as string);
  loadActivities(route.query.id as string);
});

// 加载当前用户信息
const loadCurrentUser = async (id: string) => {
  try {
    const result = await currentUserService(id);
    currentUser.value = result.data;
  } catch (error) {
    console.error('加载当前用户信息失败:', error);
  }
};

// 加载活动数据
const loadActivities = async (id: string) => {
  try {
    const result = await userLogsService(id);
    mockUserActivities.value = result.data;

    let filteredActivities = mockUserActivities.value;

    // 类型过滤
    if (activityType.value) {
      filteredActivities = filteredActivities.filter(act => act.type === activityType.value);
    }

    // 日期过滤
    if (dateRange.value && dateRange.value.length === 2) {
      const [startDate, endDate] = dateRange.value;
      filteredActivities = filteredActivities.filter(act => {
        const timestamp = new Date(act.timestamp);
        const start = new Date(`${startDate} 00:00:00`);
        const end = new Date(`${endDate} 23:59:59`);
        return timestamp >= start && timestamp <= end;
      });
    }

    // 搜索过滤
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase();
      filteredActivities = filteredActivities.filter(act =>
        act.content.toLowerCase().includes(keyword) ||
        (act.details && act.details.toLowerCase().includes(keyword))
      );
    }

    totalActivities.value = filteredActivities.length;
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const endIndex = startIndex + pageSize.value;
    activities.value = filteredActivities.slice(startIndex, endIndex);
  } catch (error) {
    console.error('加载活动数据失败:', error);
  }
};

// 获取活动类型名称
const getActivityTypeName = (type: string) => {
  const activity = activityTypes.value.find(t => t.value === type);
  return activity? activity.label : type;
};

// 获取活动图标
const getActivityIcon = (type: string) => {
  const icons: Record<string, any> = {
    read: Notebook,
    review: ChatLineRound,
    like: View,
    note: Notebook,
    login: User,
    collect: Star
  };
  return icons[type] || User;
};

// 获取活动颜色
const getActivityColor = (type: string) => {
  const colors: Record<string, string> = {
    read: 'var(--el-color-primary)',
    review: 'var(--el-color-success)',
    like: 'var(--el-color-warning)',
    note: 'var(--el-color-info)',
    login: 'var(--el-color-danger)',
    collect: '#DBDB70 '
  };
  return colors[type] || 'var(--el-text-color-secondary)';
};

// 分页相关方法
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
  loadActivities(route.query.id as string);
};

const handleCurrentUserActivities = (newPage: number) => {
  currentPage.value = newPage;
  loadActivities(route.query.id as string);
};

// 查看详情
const viewDetail = (activity: any) => {
  currentActivity.value = activity;
  detailDialogVisible.value = true;
};

// 关闭详情弹窗
const closeDetailDialog = () => {
  detailDialogVisible.value = false;
};

// 返回按钮点击事件
const goBack = () => {
  router.push('/user');
};

// 处理筛选条件变化
const handleFilterChange = () => {
  currentPage.value = 1;
  loadActivities(route.query.id as string);
};
</script>

<style scoped lang="scss">
.user-activities {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.user-header {
  margin-bottom: 20px;

  .header-content {
    display: flex;
    align-items: center;
    gap: 20px;

    .user-info {
      flex: 1;

      h2 {
        margin: 0 0 10px 0;
        font-size: 24px;
      }

      .meta-info {
        display: flex;
        gap: 20px;
        color: var(--el-text-color-secondary);
        font-size: 14px;
      }
    }
  }
}

.activities-filter {
  margin-bottom: 20px;

  .filter-row {
    display: flex;
    gap: 15px;
    align-items: center;

    .el-select {
      flex: 1;
    }

    .el-date-picker {
      flex: 2;
    }

    .el-input {
      flex: 3;
    }
  }
}

.activities-list {
  .activities-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h3 {
      margin: 0;
      font-size: 18px;
      color: #333;
    }

    .stats {
      color: #666;
      font-size: 14px;
    }
  }

  .activity-items {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }

  .activity-item {
    display: flex;
    gap: 15px;
    padding: 15px;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .activity-time {
      min-width: 160px;
      color: var(--el-text-color-secondary);
      font-size: 14px;
    }

    .activity-content {
      flex: 1;

      .activity-type {
        display: flex;
        align-items: center;
        gap: 5px;
        margin-bottom: 8px;
        font-size: 14px;
        font-weight: 500;
      }

      .activity-text {
        color: #333;
        font-weight: 500;
        margin-bottom: 5px;
      }

      .activity-preview {
        color: var(--el-text-color-secondary);
        font-size: 13px;
      }
    }

    .activity-cover {
      width: 60px;
      height: 90px;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 4px;
      }
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}

.activity-detail {
  .detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;

    .activity-time {
      color: var(--el-text-color-secondary);
    }

    .activity-type {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 16px;
      font-weight: 500;
    }
  }

  .detail-content {
    h4 {
      margin: 0 0 15px 0;
      font-size: 18px;
      color: #333;
    }

    .book-info {
      display: flex;
      align-items: center;
      gap: 15px;
      margin: 20px 0;
      padding: 15px;
      background-color: #f9f9f9;
      border-radius: 8px;

      img {
        width: 80px;
        height: 120px;
        object-fit: cover;
        border-radius: 4px;
      }

      .book-title {
        font-size: 16px;
        font-weight: 500;
      }
    }

    .activity-details {
      h5 {
        margin: 20px 0 10px 0;
        font-size: 16px;
        color: #333;
      }

      p {
        color: #666;
        line-height: 1.6;
        margin: 0;
        white-space: pre-line;
      }
    }
  }
}

@media (max-width: 768px) {
  .user-header .header-content {
    flex-direction: column;
    align-items: flex-start;

    .user-info {
      width: 100%;

      .meta-info {
        flex-direction: column;
        gap: 5px;
      }
    }
  }

  .activities-filter .filter-row {
    flex-direction: column;

    .el-select,
    .el-date-picker,
    .el-input {
      width: 100%;
      flex: auto;
    }
  }

  .activity-item {
    flex-direction: column;

    .activity-time {
      margin-bottom: 10px;
    }

    .activity-cover {
      margin-top: 10px;
      align-self: flex-start;
    }
  }
}
</style>